package com.example.data.repo;

import com.example.data.datasource.remote.RemoteDataFetcher;
import com.example.domain.result.Result;
import com.orhanobut.logger.Logger;

import java.io.IOException;

import retrofit2.Call;
import retrofit2.Response;

public abstract class BaseRemoteRepo {
    protected <T> Result<T> safeRemoteCall(RemoteDataFetcher<T> dataFetcher) {
        try {
            Call<T> call = dataFetcher.callApi();
            Response<T> data = call.execute();
            Logger.d(data.body());
            if (!data.isSuccessful()) {
                return Result.error(new IOException(), data.errorBody().string());
            } else {
                if (data.body() != null) {
                    return Result.success(data.body());
                } else {
                    return Result.error(new IllegalStateException(), "网络错误，返回数据为空");
                }
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return Result.error(throwable, "网络错误");
        }
    }
}
